<?php
require 'TVB/pms/pdes/common/bootstrap.php';

$result = array('status'=>0, 'data'=>'', 'msg'=>'failed. please retry!');
if(empty($_REQUEST['master_name'])){
	exit(json_encode($result));
}

$master = trim($_REQUEST['master_name']);

/* for bug 4173
$query = "SELECT id,master FROM cast_dictionary WHERE master=:master";
if(($rs=Model::selectBySql($query,array(':master'=>$master)))){
	$result['status'] = 1;
	$result['data'] = array(
		'id'=>$rs[0]['id'],
		'name'=>$rs[0]['master']
	);
	exit(json_encode($result));
}
 */

$sql = "INSERT INTO `cast_dictionary`
    VALUES(NULL, :master, :chi_last_name, :chi_first_name, :eng_last_name, :eng_first_name1, :eng_first_name2, :others, :see_also, :remark, :gender, :is_chinese, :created_at, :created_by, :modified_at, :modified_by)";
$param = array(
    ':master'           => $master, 
    ':chi_last_name'    => isset($_REQUEST['surname_cn']) ? $_REQUEST['surname_cn'] : '', 
    ':chi_first_name'   => isset($_REQUEST['first_cn']) ? $_REQUEST['first_cn'] : '',
    ':eng_last_name'    => isset($_REQUEST['last_name_en']) ? $_REQUEST['last_name_en'] : '',
    ':eng_first_name1'  => isset($_REQUEST['first_name1_en']) ? $_REQUEST['first_name1_en'] : '',
    ':eng_first_name2'  => isset($_REQUEST['first_name2_en']) ? $_REQUEST['first_name2_en'] : '',
    ':others'           => isset($_REQUEST['other_name']) ? $_REQUEST['other_name'] : '',
    ':see_also'         => isset($_REQUEST['see_also']) ? $_REQUEST['see_also'] : '',
    ':remark'           => isset($_REQUEST['remark']) ? $_REQUEST['remark'] : '',
    ':gender'           => isset($_REQUEST['gender']) ? $_REQUEST['gender'] : '',
    ':is_chinese'       => isset($_REQUEST['chinese']) ? 1 : 0,
    ':created_at'       => date('Y-m-d H:i:s'), 
    ':created_by'       => CommonUtils::get_user(), 
    ':modified_at'      => date('Y-m-d H:i:s'), 
    ':modified_by'      => CommonUtils::get_user(),
);
$cast_dictionary_id = Model::updateBySql($sql, $param);

$programme_id = (int)$_REQUEST['programme_id'];
change_log::updateOne(
	array(
		'type'=>'cast_dictionary',
		'keys'=>array('id'=>$cast_dictionary_id),
		'is_active'=>1,
		'is_publish'=>0,
		'programme_id'=>$programme_id
	)
);

$result['status'] = $cast_dictionary_id ? 1 : 0;
$result['data'] = array(
    'id'    => $cast_dictionary_id,
    'name'  => $_REQUEST['master_name']
    #'name'  => $_REQUEST['master_name'] . ',' . $_REQUEST['surname_cn'] . $_REQUEST['first_cn'] . ',' . $_REQUEST['last_name_en'] . ' ' . $_REQUEST['first_name1_en'] . ',' . $_REQUEST['first_name2_en'] . ' ' . $_REQUEST['last_name_en'] . ',' . $_REQUEST['other_name'] . ',' . $_REQUEST['remark']
);

echo (json_encode($result));
?>
